package io.iamting93.code.service;

import io.iamting93.api.CodeApi;
import io.iamting93.api.EmailApi;
import io.iamting93.code.dao.AuthCodeDao;
import io.iamting93.code.pojo.AuthCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author boting.guo
 * @date 2021/11/30 13:59
 */

@Slf4j
@DubboService
public class CodeService implements CodeApi {

    // 有效时间10分钟
    public static long EXPIRED_TIME = 10 * 60 * 1000;

    @Autowired
    private AuthCodeDao authCodeDao;

    @DubboReference
    private EmailApi emailApi;

    public boolean refreshCode(String emailAddress) {
        // 判断是否能刷新
        if (canRefresh(emailAddress)) {
            // 进行刷新
            String code = doRefreshCode();

            long createTimeStamp = System.currentTimeMillis();

            AuthCode authCode = new AuthCode(emailAddress, code, createTimeStamp);

            // 保存到数据库中
            authCodeDao.insertAuthCode(authCode);
            log.info("refresh code for email: " + emailAddress + " code: " + code);

            // 发送验证码给用户
            return sendCode(emailAddress, code);

        }
        return false;
    }

    @Override
    public int validateCode(String emailAddress, String code) {
        // 从数据库中获取验证码信息
        AuthCode authCode = authCodeDao.getAuthCode(emailAddress);
        // 不存在，报错
        if (authCode == null) {
            return 1;
        }
        // 是否有效
        if (authCode.getCreateTime() + EXPIRED_TIME < System.currentTimeMillis()) {
            // 超时
            return 2;
        }
        return code.equals(authCode.getCode()) ? 0 : 1;
    }

    private boolean canRefresh(String emailAddress) {
        AuthCode authCode = authCodeDao.getAuthCode(emailAddress);

        // 不存在或者超过一分钟，可以刷新
        return authCode == null || System.currentTimeMillis() - authCode.getCreateTime() > 60000;
    }

    private String doRefreshCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    private boolean sendCode(String emailAddress, String code) {
//       return emailApi.sendEmail(emailAddress, code);
         return true;
    }

}
